package com.ken.android.music.view.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ken.android.music.db.MusicDao;
import com.ken.android.music.model.MusicBean;
import com.ken.android.music.mvp.B.BasePresenter;
import com.ken.android.music.view.fragment.AlbumDetailFragment;
import com.ken.android.music.service.PlayerService;
import com.ken.android.music.R;
import com.ken.android.music.service.ComponentUtil;
import com.ken.android.music.view.presenter.MusicPlayingContract;
import com.ken.android.music.view.presenter.MusicPlayingPresenter;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentPagerAdapter;

/**
 * Created by axnshy on 16/7/29.
 */
public class MusicPlayingActivity extends BaseAudioActivity<MusicPlayingContract.View, MusicPlayingPresenter> implements Observer,MusicPlayingContract.View {

    @ViewInject(R.id.tb_musicplaying_top)
    private Toolbar toolbar;
    @ViewInject(R.id.iv_back)
    private ImageView returnImg;
    @ViewInject(R.id.tv_viewTitle)
    private TextView toolbar_title;
    @ViewInject(R.id.progressbar_player_status)
    private SeekBar playStatusBar;
    @ViewInject(R.id.tv_musicPlay_currentLocation)
    private TextView playStatusCurrent;
    @ViewInject(R.id.tv_musicPlay_totalTime)
    private TextView playStatusTotal;
    @ViewInject(R.id.iv_repeat_play)
    private ImageView musicRepeatImg;
    @ViewInject(R.id.iv_previous_play)
    private ImageView musicPrevImg;
    @ViewInject(R.id.iv_play)
    private ImageView musicPlayImg;
    @ViewInject(R.id.iv_next_play)
    private ImageView musicNextImg;
    @ViewInject(R.id.iv_shuffle_play)
    private ImageView musicShuffleImg;
    @ViewInject(R.id.iv_current_musicAlbumCover)
    private ImageView artWorkImg;
    @ViewInject(R.id.tv_current_musicName)
    private TextView CurrentMusicNameTx;
    @ViewInject(R.id.tv_current_musicArtist)
    private TextView CurrentArtWorkTx;

    private Context context;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                playStatusBar.setProgress((int) msg.obj);
//                    playStatusCurrent.setText(MusicBean.parseMusicData());
                    break;
                case 1:  Bitmap bm = BitmapFactory.decodeFile((String) msg.obj);
                    BitmapDrawable bmpDraw = new BitmapDrawable(bm);
                    artWorkImg.setImageDrawable(bmpDraw);
                    break;
            }
        }
    };

    @Event(value = {R.id.iv_back, R.id.iv_toolbar_music_share, R.id.iv_repeat_play, R.id.iv_previous_play, R.id.iv_play, R.id.iv_next_play, R.id.iv_shuffle_play})
    private void OnClicked(View view) {
        //判断Service是否存在

        if (!ComponentUtil.isMyServiceRunning(context, PlayerService.class)) {
            Intent serviceintent = new Intent(context, PlayerService.class);
            startService(serviceintent);
            Log.e("TAGS", "MediaPlayerService does not existed");
        } else {
            Log.e("TAGS", "MediaPlayerService existed");

        }
        switch (view.getId()) {
            case R.id.iv_repeat_play:
                if (getControllerCompat().getRepeatMode() == 0) {
                    musicRepeatImg.setBackgroundResource(R.drawable.basecopy);
                } else {
                    musicRepeatImg.setBackgroundResource(R.drawable.base);
                }
                break;
            case R.id.iv_shuffle_play:
                if (getControllerCompat().getShuffleMode() == 0) {
                    musicShuffleImg.setBackgroundResource(R.drawable.basecopy);
                } else {
                    musicShuffleImg.setBackgroundResource(R.drawable.base);
                }
                break;
            case R.id.iv_previous_play:
                getTransports().skipToPrevious();
                break;
            case R.id.iv_next_play:
                getTransports().skipToNext();
                break;
            case R.id.iv_play: {
                if (getPlaybackState().getState() == PlaybackStateCompat.STATE_PLAYING) {
                    getTransports().pause();
                } else {
                    getTransports().play();
                }
                break;
            }
            case R.id.iv_back:
                onBackPressed();
                break;
        }
        updateUI();
    }

    private FragmentPagerAdapter pagerAdapter;
    private List<AlbumDetailFragment> fragmentArrayList;


    @Override
    public int onSetContent() {
        return R.layout.music_play;
    }

    @Override
    public MusicPlayingPresenter createPresenter() {
        return new MusicPlayingPresenter();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.music_play);
        context=this;
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorIndego));
        initView();

    }


    private void initView() {
        fragmentArrayList = new ArrayList<>();


    }

    @Override
    public void update(Observable observable, Object o) {

        updateUI();
    }

    private void updateUI() {
        //PlayerState代表播放状态
        switch (getPlaybackState().getState()) {
            case PlaybackStateCompat.STATE_PLAYING:
            case PlaybackStateCompat.STATE_STOPPED: {
                musicPlayImg.setImageResource(R.drawable.play);
                //Toast.makeText(context, "music is prepared", Toast.LENGTH_SHORT).show();
                break;
            }
            case PlaybackStateCompat.STATE_PAUSED: {
                musicPlayImg.setImageResource(R.drawable.pause);
                //Toast.makeText(context, "music is playing", Toast.LENGTH_SHORT).show();
                break;
            }//Toast.makeText(context, "music is paused", Toast.LENGTH_SHORT).show();

        }
//        CurrentMusicNameTx.setText(mService.currentMusic.getMusicName());
//        CurrentArtWorkTx.setText(mService.currentMusic.album);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                String albumArt = MusicDao.getAlbumArt(MusicPlayingActivity.this, mService.currentMusic.albumId);
//                Log.e("TAG","albumArt-----------------------"+albumArt);
//                Message msg = Message.obtain();
//                msg.obj = albumArt;
//                Log.w("TAG","AlbumArtWork-----------"+albumArt);
//                msg.what=1;
//                handler.sendMessage(msg);
//            }
//        }).start();
//        playStatusTotal.setText(mService.currentMusic.getMusicTimeTotal());
//        playStatusBar.setMax((int) (mService.currentMusic.duration/1000));
//        Log.w("TAG","TotalProgress-----------"+mService.currentMusic.duration/1000);
//       new Thread(new Runnable() {
//           @Override
//           public void run() {
//               while(mService.getPlayerState()==mService.MediaPlayer_PLAY){
//                   Message msg=Message.obtain();
//                   int progress=mService.getPlayerInstance().getCurrentPosition()/1000;
//                   msg.obj=progress;
//                   Log.w("TAG","progress-----------"+progress);
//                   msg.what=0;
//                   handler.sendMessage(msg);
//                   try {
//                       Thread.sleep(1000);
//                   } catch (InterruptedException e) {
//                       e.printStackTrace();
//                   }
//               }
//
//           }
//       }).start();
/*
        MusicInfo currentMusic = mService.currentMusic;
        int position = mService.getMyList().indexOf(currentMusic);
        MusicInfo previous = new MusicInfo(), next = new MusicInfo();
        if (position == mService.getMyList().size() - 1) {
            previous = mService.getMyList().get(position - 1);
            next = mService.getMyList().get(0);
        }
        if (position == 0) {
            previous = mService.getMyList().get(mService.getMyList().size() - 1);
            next = mService.getMyList().get(1);
        }
        if (position != 0 && position != mService.getMyList().size() - 1) {
            previous = mService.getMyList().get(mService.getMyList().size() - 1);
            next = mService.getMyList().get(position + 1);
        }

        AlbumDetailFragment currentFragment = new AlbumDetailFragment();
        AlbumDetailFragment previousFragment = new AlbumDetailFragment();
        AlbumDetailFragment nextFragment = new AlbumDetailFragment();
        Bundle curBundle = new Bundle();
        curBundle.putParcelable("MusicInfo", currentMusic);
        Bundle prevBundle = new Bundle();
        prevBundle.putParcelable("MusicInfo", previous);
        Bundle nextBundle = new Bundle();
        nextBundle.putParcelable("MusicInfo", next);
        currentFragment.setArguments(curBundle);
        previousFragment.setArguments(prevBundle);
        nextFragment.setArguments(nextBundle);
        fragmentArrayList.add(0, previousFragment);
        fragmentArrayList.add(1, currentFragment);
        fragmentArrayList.add(2, nextFragment);
        FragmentManager manager = getSupportFragmentManager();
        pagerAdapter = new FragmentPagerAdapter(manager) {
            @Override
            public Fragment getItem(int position) {
                return fragmentArrayList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentArrayList.size();
            }
        };
        viewPager.setAdapter(pagerAdapter);*/
    }
}
